package com.zhkj.txg.module.home.adapter

import android.widget.RadioButton
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.zhkj.txg.R
import com.zhkj.txg.module.home.entity.ShopInfo

class ShopListAdapter : BaseQuickAdapter<ShopInfo, BaseViewHolder>(R.layout.item_shop_list) {

    var index: Int = -1

    init {
        setOnItemClickListener { _, _, position ->
            val rbShopListChoice = getViewByPosition(position, R.id.rbShopListChoice)
                    as RadioButton
            if (!rbShopListChoice.isChecked) {
                rbShopListChoice.isChecked = true
                index = position
                notifyDataSetChanged()
            }
        }
    }

    override fun convert(helper: BaseViewHolder, item: ShopInfo) {
        helper.setText(R.id.tvShopName, item.shop_name)
            .setText(R.id.tvShopAddress, item.address)
            .setText(R.id.tvShopIsDelivery, if (item.isDelivery == 0) "自提" else "配送")
            .setText(R.id.tvShopDistance, "${item.distance}km")

        val businessTime = item.businessTime
        helper.setText(R.id.tvShopBusinessTime, if (businessTime == null) "" else "营业时间:${businessTime.startTime}--${businessTime.endTime}")
        helper.setGone(R.id.tvShopBusinessTime, businessTime == null)

        val rbShopListChoice = helper.getView<RadioButton>(R.id.rbShopListChoice)
        rbShopListChoice.isChecked = index == getItemPosition(item)
//        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
//        val shopInfo2 = try {
//            val gson = Gson()
//            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
//        } catch (e: Exception) {
//            null
//        }
//        if (shopInfo2 != null) {
//            if (shopInfo2.id == item.id) {
//                rbShopListChoice.isChecked = true
//                index = getItemPosition(item)
//            } else {
//                rbShopListChoice.isChecked = false
//            }
//        } else {
//            rbShopListChoice.isChecked = false
//        }
    }

    fun getShopInfo(): ShopInfo? {
        if (index == -1)
            return null
        return data[index]
    }

}